/*******************************************************************************
 * Copyright (c) 2014-8-21 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.web.controller;

import com.foreveross.project.projectonline.config.Constants;
import com.foreveross.project.projectonline.jfinal.render.CaptchaRender;
import com.foreveross.project.projectonline.model.TpMgtUser;
import com.foreveross.project.projectonline.service.MgtUserService;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.spring.Inject;
import com.jfinal.plugin.spring.IocInterceptor;

/**
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-8-21
 */
@Before(IocInterceptor.class)
public class LoginController extends BaseController {

	@Inject.BY_NAME
	MgtUserService mgtUserService;

	public void index() {
		//render("/pages/201410/login/login.html");
		render("/pages/login.html");
	}

	public void login() {
		//addErrors(!CaptchaRender.validate(getRequest()), Constants.DEFAULT_CAPTCHA_CODE_KEY, "验证码不正确");
		if (hasErrors()) {
			index();
			return;
		}
		String email = getPara("LOGIN_EMAIL");
		addErrors(StrKit.isBlank(email), "LOGIN_EMAIL", "请输入账号/邮箱");
		String passwd = getPara("LOGIN_PASSWD");
		addErrors(StrKit.isBlank(passwd), "LOGIN_PASSWD", "请输入密码");
		if (hasErrors()) {
			index();
			return;
		}
		TpMgtUser user = mgtUserService.login(email, passwd);
		addErrors(user == null, "LOGIN_EMAIL", "用户名或密码错误");
		if (hasErrors()) {
			index();
			return;
		}
		String redirectUrl = (String) getRequest().getSession().getAttribute(Constants.SESSION_LOGIN_BEFORE_URL);
		{
			getRequest().getSession().invalidate();
			getRequest().getSession(true);
		}
		setLogin(user);
		if (redirectUrl != null) {
			redirect(redirectUrl);
		} else {
			redirect("/");
		}
	}

	public void logout() {
		setLogin(null);
		redirect("/");
	}

}
